package com.api.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.api.log.Log;
import com.api.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传
 * @Author: yangsf
 * @CreateDate: 2024/9/24
 */
@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController extends BaseController {

    @Value("${imgServer.networkUrl}")
    public String networkUrl;

    @Value("${imgServer.localUrl}")
    public String localUrl;


    /**
     * 头像上传
     * 接口：/upload/uploadAvatar
     * @param file
     * @return
     */
    @Log("头像上传")
    @RequestMapping("/uploadAvatar")
    public Result uploadAvatar(@RequestParam(value = "file",required = true) MultipartFile file){
        Map<String,Object> res = new HashMap<String, Object>();
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取图片名后缀
        String ext = "." + originalFilename.split("\\.")[1];
        //使用UUID生成图片名，防止名称一样
        UUID id= UUID.randomUUID();
        String idd=id.toString().split("-")[0];//生成8位数长度的随机十六进制
        String fileName = idd.toString().replace("-","") + ext;
        String key = "avatar/";
        //校验是否存在路径，不存在则创建
        File targetFile = new File(localUrl+key);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        InputStream ins = null;
        File toFile = null;
        try {
            ins = file.getInputStream();
            toFile = new File(localUrl+key+fileName);
            inputStreamToFile(ins, toFile);
            ins.close();
        } catch (IOException e) {
            throw new RuntimeException("上传失败");
        }
        res.put("url", networkUrl + key + fileName);
        return Result.ok(res);
    }


    /**
     * 图片上传 - 本地存储
     * 接口：/upload/localUpload
     * @param file
     * @return
     */
    @Log("图片上传 - 本地存储")
    @RequestMapping("/localUpload")
    public Result localUpload(@RequestParam(value = "file",required = true) MultipartFile file){
        if (file.isEmpty()) {
            return Result.err("上传失败");
        }
        Map<String,Object> res = new HashMap<String, Object>();
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取图片名后缀
        String ext = "." + originalFilename.split("\\.")[1];
        //使用UUID生成图片名，防止名称一样
        UUID id= UUID.randomUUID();
        String idd=id.toString().split("-")[0];//生成8位数长度的随机十六进制
        String fileName = idd.toString().replace("-","") + ext;
        String key = DateUtil.format(new Date(), "yyyy/MM/dd") + "/";
        //校验是否存在路径，不存在则创建
        File targetFile = new File(localUrl+key);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        InputStream ins = null;
        File toFile = null;
        try {
            ins = file.getInputStream();
            toFile = new File(localUrl+key+fileName);
            inputStreamToFile(ins, toFile);
            ins.close();
        } catch (IOException e) {
            return Result.imgErr("上传失败");
        }
        res.put("url", networkUrl + key + fileName);
        return Result.imgSuccess(res);
    }

    /**
     *  读取图片
     * **/
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

